package com.facebook.android;

import java.util.Collections;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import com.appengine.utils.SavingAndLoadingCenter;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.ImageView;

public enum FBimageManagerV2 {
	INSTANCE;
	private final ExecutorService pool;
	private Map<ImageView, String> imageViews = Collections
			.synchronizedMap(new WeakHashMap<ImageView, String>());
	private Bitmap placeholder;

	FBimageManagerV2() {
		pool = Executors.newFixedThreadPool(5);
	}

	public void setPlaceholder(Bitmap bmp) {
		placeholder = bmp;
	}

	public Bitmap getBitmapFromCache(String fbID, Context c) {
		Bitmap img = SavingAndLoadingCenter.loadFriendImage(fbID, c);
		if (img != null) {
			return img;
		}

		return null;
	}

	public void queueJob(final String fbID, final ImageView imageView, final Context c) {
		/* Create handler in UI thread. */
		final Handler handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				String tag = imageViews.get(imageView);
				if (tag != null && tag.equals(fbID)) {
					if (msg.obj != null) {
						imageView.setImageBitmap((Bitmap) msg.obj);
					} else {
						imageView.setImageBitmap(placeholder);
						Log.d(null, "fail " + fbID);
					}
				}
			}
		};

		pool.submit(new Runnable() {
			@Override
			public void run() {
				final Bitmap bmp = downloadBitmap(fbID, c);
				Message message = Message.obtain();
				message.obj = bmp;
				Log.d(null, "Item downloaded: " + fbID);

				handler.sendMessage(message);
			}
		});
	}

	public void loadBitmap(final String fbID, final ImageView imageView,
			Context c) {
		imageViews.put(imageView, fbID);
		Bitmap bitmap = getBitmapFromCache(fbID, c);

		// check in UI thread, so no concurrency issues
		if (bitmap != null) {
			Log.d(null, "Item loaded from cache: " + fbID);
			imageView.setImageBitmap(bitmap);
		} else {
			imageView.setImageBitmap(placeholder);
			queueJob(fbID, imageView, c);
		}
	}

	private Bitmap downloadBitmap(String fbID, Context c) {
		Bitmap bitmap = null;
		bitmap = FacebookUtils.GetProfilePic(fbID, "square");
		SavingAndLoadingCenter.saveFriendImage(fbID, bitmap, c);
		return bitmap;

	}
}